<template>
  <div class="container">
    <el-row class="header">
      <el-col class="asd" :span="10" align="left">
        <el-input
          clearable
          icon="el-icon-search"
          v-model="data.params.projectName"
          placeholder="项目名称/合同编号"
          style="width: 220px; margin-right: 15px"
        />
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="14" align="right">
        <el-button v-limit="'XMZX:SCYS:XMYS:EXPORT'" class="ordinary" @click="exportExcel()"
          >批量导出</el-button
        >
        <el-button v-limit="'XMZX:SCYS:XMYS:APPLY'" type="primary" @click="handleApplication()"
          >验收申请</el-button
        >
        <el-button v-limit="'XMZX:SCYS:XMYS:STOP'" type="danger" @click="stopApplication()"
          >终止申请</el-button
        >
        <el-button v-limit="'XMZX:SCYS:XMYS:ACCEPT'" type="primary" @click="handleAcceptance()"
          >项目验收</el-button
        >
      </el-col>
    </el-row>

    <Table
      :loading="data.isLoading"
      :tableArr="data.allTableData"
      :columns="data.columns"
      :page-size="data.params.size"
      :page-num="data.params.current"
      @selectList="getCurrentList"
      @row-click="handleRowClick"
    >
      <template #status>
        <el-table-column label="验收状态" width="80">
          <template #default="{ row }">
            <span class="pending" v-if="row.status == 0">待验收</span>
            <span class="approved" v-if="row.status == 1">已完成</span>
            <span class="rejection" v-if="row.status == 2">已驳回</span>
            <span class="rejection" v-if="row.status == 3">已中止</span>
          </template>
        </el-table-column>
      </template>
      <template #operate="{ row }">
        <el-button
          v-limit="'XMZX:SCYS:XMYS:DETAIL'"
          size="small"
          class="ordinary"
          @click="handleDetail(row)"
          >详情</el-button
        >
      </template>
    </Table>
    <div class="example-pagination-block">
      <el-pagination
        background
        layout="prev, pager, next ,total,sizes,jumper"
        :total="data.total"
        :page-size="data.params.size"
        v-model:current-page="data.params.current"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <el-dialog v-model="data.editDialog" width="60%" title="验收详情" @close="closeDetail">
      <el-tabs v-model="data.activeName" class="demo-tabs box">
        <el-tab-pane label="基本信息" name="1">
          <application title="验收详情" ref="applicationForm" v-if="data.editDialog"></application>
        </el-tab-pane>
        <el-tab-pane
          label="验收意见"
          name="2"
          v-if="data.currentRow.status == 1 || data.currentRow.status == 2"
        >
          <acceptance title="验收详情" :isDigit="data.isDigit" v-if="data.editDialog"></acceptance>
        </el-tab-pane>
      </el-tabs>
      <!-- <application title="验收详情" ref="applicationForm" v-if="data.editDialog"></application> -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.editDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="data.acceptanceDialog" width="60%" title="项目验收">
      <acceptance ref="acceptanceRef" :isDigit="data.isDigit" v-if="data.acceptanceDialog"></acceptance>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.acceptanceDialog = false">关闭</el-button>
          <el-button type="danger" @click="handleAcceptanceFail()">验收不通过</el-button>
          <el-button type="primary" @click="handleAcceptanceSave()">验收通过</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="data.applicationDialog" width="60%" title="项目验收申请">
      <application
        title="项目验收申请"
        ref="applicationForm"
        v-if="data.applicationDialog"
      ></application>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.applicationDialog = false">关闭</el-button>
          <el-button type="primary" @click="saveApplication()">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导出字段选择 -->
    <Export
      :detailList="data.detailList"
      :showing="data.exportDialog"
      @close="closeExport"
      @handle-filed="handleFiled"
    ></Export>
  </div>
</template>

<script lang="ts">
import { reactive, ref } from 'vue'
import { useStore } from 'vuex'
import {
  acceptanceProjects,
  acceptanceSave,
  getExportExcel,
  getProductList,
  terminate,
  getDetail,
} from '../../api/acceptance'
import Table from '../../components/table2/table.vue'
import acceptance from './components/acceptance.vue'
import application from './components/application.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import tableData from './tableHeader.json'
import Export from '@/views/project/components/Export/index.vue'

export default {
  components: {
    Table,
    acceptance,
    application,
    Export,
  },
  setup() {
    const store = useStore()
    let data = reactive({
      params: {
        current: 1,
        size: 10,
        projectName: '',
      },
      total: 0,
      allTableData: [],
      activeName: '1',
      columns: tableData.platformTableHeader,
      ids: [],
      currentList: [] as any,
      isLoading: false,
      editDialog: false,
      acceptanceDialog: false,
      applicationDialog: false,
      currentRow: {} as any,
      exportDialog: false,
      detailList: [] as any,
      isDigit:false
    })
    const applicationForm = ref()
    const acceptanceRef = ref()
    const search = () => {
      data.params.current = 1
      onSearch()
    }
    const onSearch = () => {
      data.isLoading = true
      getProductList(data.params).then((res) => {
        data.allTableData = res.data.data.records
        data.allTableData.map((item) => {
          ;(item as any).periodTime =
            (item as any).startTime.slice(0, 10) + '至' + (item as any).endTime.slice(0, 10)
          ;(item as any).createTime = (item as any).createTime.slice(0, 10)
        })
        data.total = res.data.data.total
        data.isLoading = false
      })
    }
    const getCurrentList = (currentList) => {
      console.log(currentList, 'currentList')
      data.currentList = currentList
      data.ids = currentList.map((item) => {
        return item.id
      })
    }
    onSearch()
    const handleRowClick = (row) => {
      handleDetail(row)
    }
    const handleDetail = (row) => {
      console.log(row,'handleRowClick');
      data.isDigit = row.projectCategory==2
      data.currentRow = row
      if(data.currentRow.status == 1 || data.currentRow.status == 2){
        for (let key in store.state.projectCenter.projectAcceptanceForm) {
          store.state.projectCenter.projectAcceptanceForm[key] = row[key]
        }
      }
      getDetail(row.id).then((res) => {
        console.log(res.data.data, '进度执行详情')
        for (let key in store.state.projectCenter.applicationForm) {
          store.state.projectCenter.applicationForm[key] = res.data.data[key]
        }
        // if(data.currentRow.status == 1 || data.currentRow.status == 2){
        //   for (let key in store.state.projectCenter.projectAcceptanceForm) {
        //     store.state.projectCenter.projectAcceptanceForm[key] = res.data.data[key]
        //   }
        //   console.log(res.data.data,store.state.projectCenter.projectAcceptanceForm,'store.state.projectCenter.projectAcceptanceForm');
        // }
        data.editDialog = true
      })
    }
    //改变页码
    const handleCurrentChange = (e) => {
      console.log(e, 'handleCurrentChange')
      data.params.current = e
      onSearch()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      console.log(e, 'handleSizeChange')
      data.params.size = e
      data.params.current = 1
      onSearch()
    }
    const handleDel = () => {
      if (data.ids.length) {
        ElMessageBox.alert('您确认删除所选中数据吗？', '提示', {
          confirmButtonText: '确认',
          callback: (action) => {
            console.log(action)
          },
        })
      }
    }
    const closeDetail = ()=>{
      data.activeName ='1'
    }
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          getExportExcel({ ...data.params, ids: data.ids, headList: arr })
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const exportExcel = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'startTime', title: '项目起止时间' },
        // { fieldName: 'endTime', title: '结束时间' },
        { fieldName: 'contractNumber', title: '合同编号' },
        { fieldName: 'affiliatedUnit', title: '所属单位' },
        { fieldName: 'projectLeader', title: '项目负责人' },
        { fieldName: 'checkType', title: '验收类型' },
        { fieldName: 'requestInstructions', title: '申请验收说明' },
        { fieldName: 'applyPerson', title: '申请人' },
        { fieldName: 'createTime', title: '申请时间' },
      ]
    }
    // const exportExcel = () => {
    //   ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }).then(() => {
    //     getExportExcel(data.params.projectName, data.ids)
    //   })
    // }
    const stopApplication = () => {
      if (data.ids.length) {
        let flag = true
        data.currentList.forEach((item) => {
          if (item.status != 0) {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '只能中止待验收的申请',
            type: 'warning',
          })
          return
        }
        ElMessageBox.confirm('您确认终止申请选中数据吗？', '终止申请', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          let params = data.ids.map((id) => {
            return {
              id,
              checkType: '项目中止',
              status: 3,
            }
          })
          terminate(params).then((res) => {
            console.log(res)
            if (res.data.code == 200) {
              onSearch()
              ElMessage({
                message: '操作成功',
                type: 'success',
              })
            }
          })
        })
      } else {
        ElMessage({
          message: '请至少选择一个项目',
          type: 'warning',
        })
      }
    }
    const handleAcceptance = () => {
      if (data.ids.length) {
        let flag = true
        data.currentList.forEach((item) => {
          if (item.status != 0) {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '只能验收待验收的申请',
            type: 'warning',
          })
          return
        }
        data.isDigit = data.currentList.every(item=>{
          return item.projectCategory==2
        })
        console.log(data.isDigit,'data.isDigit');
        data.acceptanceDialog = true
      } else {
        ElMessage({
          message: '请至少选择一个项目',
          type: 'warning',
        })
      }
    }
    const handleApplication = () => {
      data.applicationDialog = true
      // 清除form表单的值
      store.commit('projectCenter/emptyAcceptanceForm')
    }
    //驳回验收申请
    const handleAcceptanceFail = () => {
      acceptanceRef.value.submitForm().then(() => {
        let params = data.ids.map((id) => {
          let obj = {
            id,
            status: 2,
            details:[] as any
          }
          for (let key in store.state.projectCenter.projectAcceptanceForm) {
            obj[key] = store.state.projectCenter.projectAcceptanceForm[key]
          }
          obj.details.forEach(item=>{
            item.projectId = id
          })
          return obj
        })
        data.acceptanceDialog = false
        acceptanceProjects(params).then((res) => {
          console.log(res)
          if (res.data.code == 200) {
            ElMessage({
              message: '操作成功',
              type: 'success',
            })
            onSearch()
          }
        })
      })
    }
    //通过验收申请
    const handleAcceptanceSave = () => {
      acceptanceRef.value.submitForm().then(() => {
        let params = data.ids.map((id) => {
          let obj = {
            id,
            status: 1,
            details:[] as any
          }
          for (let key in store.state.projectCenter.projectAcceptanceForm) {
            obj[key] = store.state.projectCenter.projectAcceptanceForm[key]
          }
          obj.details.forEach(item=>{
            item.projectId = id
          })
          return obj
        })
        data.acceptanceDialog = false
        acceptanceProjects(params).then((res) => {
          console.log(res)
          if (res.data.code == 200) {
            ElMessage({
              message: '操作成功',
              type: 'success',
            })
            onSearch()
          }
        })
      })
    }
    const saveApplication = () => {
      applicationForm.value.submitForm().then((res) => {
        console.log(res)
        acceptanceSave(store.state.projectCenter.applicationForm).then((res) => {
          if (res.data.code == 200) {
            console.log(res, 'acceptanceSave')
            data.applicationDialog = false
            onSearch()
          }
        })
      })
    }
    return {
      data,
      applicationForm,
      acceptanceRef,
      getCurrentList,
      handleDetail,
      handleRowClick,
      handleDel,
      closeDetail,
      handleCurrentChange,
      handleSizeChange,
      handleAcceptance,
      handleApplication,
      handleAcceptanceSave,
      saveApplication,
      handleAcceptanceFail,
      exportExcel,
      closeExport,
      handleFiled,
      stopApplication,
      search,
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  // padding: 0 20px 20px;
  padding: 20px;
}
.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/deep/.demo-tabs > .el-tabs__content {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

/deep/.demo-tabs > .el-tabs__content::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}
:deep(.el-dialog__body) {
  display: block;
}
</style>
